package com.collectplus.express.app;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Bitmap;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.ProgressBar;

import com.shouhuobao.ui.R;

import droid.frame.ui.dialog.BaseDialog;
import droid.frame.utils.http.BitmapUtils;
import droid.frame.utils.http.HttpCallback;
import droid.frame.utils.http.HttpLoader;
import droid.frame.utils.http.HttpReq;

@SuppressLint("SetJavaScriptEnabled")
public class AppWebDialog extends BaseDialog {

	private WebView mWebView;
	private ImageView mImageView;
	private ProgressBar mProgressBar;
	private Activity context;

	public AppWebDialog(Activity context) {
		// 带主题样式
		super(context);
		setContentView(R.layout.app_webview_dialog);
		// setWidth(1.2F);
		this.context = context;
		//
		mWebView = (WebView) findViewById(R.id.dialog_webview);
		mImageView = (ImageView) findViewById(R.id.dialog_image);
		mProgressBar = (ProgressBar) findViewById(R.id.dialog_progressbar);
		findViewById(R.id.dialog_close).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// 点击dialog空白处，关闭dialog
				dismiss();
			}
		});
		// mWebView.setBackgroundColor(0); // 设置背景色
		WebSettings webSettings = mWebView.getSettings();
		webSettings.setJavaScriptEnabled(true);
		mWebView.setWebViewClient(new WebViewClient() {
			@Override
			public void onPageFinished(WebView view, String url) {
				super.onPageFinished(view, url);
				// mImage.setVisibility(View.GONE);
			}

			@Override
			public void onPageStarted(WebView view, String url, Bitmap favicon) {
				super.onPageStarted(view, url, favicon);
			}
		});

	}

	public void showWebView(String url) {
		mWebView.setVisibility(View.VISIBLE);
		mImageView.setVisibility(View.GONE);
		mProgressBar.setVisibility(View.GONE);
		mWebView.loadUrl(url);
		super.show();
	}

	public void showImage(final String imageUrl) {
		mWebView.setVisibility(View.GONE);
		mImageView.setVisibility(View.VISIBLE);
		mProgressBar.setVisibility(View.VISIBLE);

		// HttpLoader.getInstance().loadImage(url + "", mImageView, context);
		Bitmap bmpCache = BitmapUtils.loadBitmapFromLocal(imageUrl);
		if (bmpCache != null) {
			mImageView.setImageBitmap(bmpCache);
			mProgressBar.setVisibility(View.GONE);// 取消加载框
		} else {
			HttpLoader.getInstance().sendReq(new HttpReq(imageUrl, new HttpCallback() {
				@Override
				public void onSuccess(final Object result) {
					context.runOnUiThread(new Runnable() {
						@Override
						public void run() {
							Bitmap loadedImage = (Bitmap) result;
							BitmapUtils.cacheBitmapToFile(loadedImage, imageUrl);
							mImageView.setImageBitmap(loadedImage);
							mProgressBar.setVisibility(View.GONE);
						}
					});
				}
			}));
		}
		super.superShow();
	}
}
